package com.et114.modules.org.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.et114.components.acegi.Constants;
import com.et114.components.ectable.EXTableUtils;
import com.et114.components.ectable.EctableConverts;
import com.et114.core.action.BaseDispatchAction;
import com.et114.core.common.CONST;
import com.et114.core.common.Error;
import com.et114.core.exception.CheckException;
import com.et114.modules.org.form.TitleForm;
import com.et114.modules.org.message.OrgMessageManager;
import com.et114.modules.org.services.GroupManager;
import com.et114.modules.org.services.OrgFactory;
import com.et114.modules.org.services.RoleManager;
import com.et114.modules.org.utility.SessionUserInfo;
import com.et114.modules.org.vo.GroupVo;
import com.et114.modules.org.vo.TitleMsgVo;
import com.et114.modules.system.dictionary.DictionaryCache;

//@author zhouxy , guanhw
public class TitleAction extends BaseDispatchAction {
	public ActionForward listTitle ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		HttpSession session = request.getSession ( ) ; 
		TitleForm titleForm = ( TitleForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request );		
		
		byte currentUserMaxRoleType = currentUser.getCurrentUserMaxRoleType ( ) ;
		if ( currentUserMaxRoleType == Constants.ROLE_TYPE_ORG_MANAGER ) {  
			if (  session.getAttribute ( GroupAction.grpCheckStr ) != null && 
					!( ( Map ) session.getAttribute ( GroupAction.grpCheckStr ) ).containsKey ( titleForm.getGrpId ( ) )
					/*!OrgFactory.getGroupManager ( ).checkGrpManager( currentUser.getUserId ( ) , groupVo.getGrpId ( ) ) */ )   {
				error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.group.manager.noauth" , request.getLocale ( ) ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "grouperror" ) ;
			}
		}		
		
		TitleMsgVo titleMsgVo = new TitleMsgVo ( );
		BeanUtils.copyProperties ( titleMsgVo , titleForm );
		
        EctableConverts  ec = titleMsgVo.getEconverts ( ) ; 
        ec.setProConvert ( "crtTime" , "a.crtTime" ) ;
        ec.setProConvert ( "titleName" , "a.titleName" ) ;
        
		EXTableUtils.initLimitPage(  titleMsgVo , request ) ;
		Long lr = OrgFactory.getTitleManager ( ).countqueryTitlesOfGroup ( titleForm.getGrpId ( ) ) ;
		titleMsgVo.setTotalRows ( lr.intValue ( ) ) ; 
		EXTableUtils.setLimitRowAttributes(  titleMsgVo , request ) ;
	
		List titleList = OrgFactory.getTitleManager ( ).queryTitlesOfGroupPage ( titleMsgVo ) ; //getGroupManager ( ).queryTitleNodesOfGroup ( titleMsgVo.getGrpId ( ) );
		titleForm.setTitleList ( titleList );
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUserMaxRoleType ) ) ;				
		return mapping.findForward ( "titleList" );
	}
	
	public ActionForward editTitle ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		TitleForm titleForm = ( TitleForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request );
		List authTypes = DictionaryCache.getInstance ( ).listBizOptions ( Constants.RESOURCE_DO_AUTH_KEY , false )   ;
		if ( titleForm.isValidTitleId ( ) ) {
			TitleMsgVo titleVo = getGroupManager ( ).loadTitle ( titleForm.getTitleId ( ) );
			BeanUtils.copyProperties ( titleForm , titleVo );
		}
		if ( authTypes.size ( ) == 2 ) request.setAttribute ( "showRadio" , "base" ) ; 
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUser.getUserRoleType ( ) ) ) ;				
		return mapping.findForward ( "titleEdit" );
	}
	
	public ActionForward editTitleAuth ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		TitleForm titleForm = ( TitleForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request );		
		TitleMsgVo title = new TitleMsgVo (  ) ;
		PropertyUtils.copyProperties ( title , titleForm ) ;
		
		EctableConverts  ec = title.getEconverts ( ) ; 
        ec.setProConvert ( "crtTime" , "a.crtTime" ) ;
		EXTableUtils.initLimitPage(  title , request ) ;
		Long lr = OrgFactory.getTitleManager ( ).countgetRolesByTitle ( title ) ;
		title.setTotalRows ( lr.intValue ( )) ; 
		EXTableUtils.setLimitRowAttributes (  title , request ) ;
		List roles = OrgFactory.getTitleManager ( ).getRolesByTitle (	title , CONST.PAGE );
		if ( titleForm.getRoleName ( ) != null )   request.setAttribute ( "roleName" , titleForm.getRoleName ( ) );
		if ( titleForm.getStartTime ( ) != null )   request.setAttribute ( "startTime" , titleForm.getStartTime ( ) );
		if ( titleForm.getEndTime ( ) != null )   request.setAttribute ( "endTime" , titleForm.getEndTime ( ) );
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUser.getUserRoleType ( ) ) ) ;								
		request.setAttribute ( "titleOfRoles" , roles );
		return mapping.findForward ( "titleAuths" );
	}
	
	
	public ActionForward toAuthIndex ( ActionMapping mapping ,
			ActionForm form , HttpServletRequest request ,
			HttpServletResponse response ) throws Exception {
		SessionUserInfo currentUser = getCurrentUser ( request ) ; 		
		byte roleType = currentUser.getUserRoleType ( ) ; 
		List soptions = OrgFactory.getRoleManager ( ).getRoleTypes ( roleType , false )  ;
		request.setAttribute ( "options" , soptions ) ;	
		return mapping.findForward ( "authIndex" );
	}

	
	public  ActionForward loadRoleAuths( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		TitleForm titleForm = ( TitleForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request );
		//load all roles
		RoleManager roleManager = OrgFactory.getRoleManager ( ) ;
		List roles = roleManager.getRoles (  titleForm.getRoleType ( ) ) ; 
		request.setAttribute ( "roles" , roles ) ;
		
		//load select roles
		TitleMsgVo title = new TitleMsgVo (  ) ;
		PropertyUtils.copyProperties ( title , titleForm ) ;
		List titleOfRoles = OrgFactory.getTitleManager ( ).getRolesByTitleNPage (	title );
		request.setAttribute ( "titleOfRoles" , titleOfRoles );	
		request.setAttribute ( Constants.CURRENT_URSER_MAX_ROLETYPE , new Integer( currentUser.getUserRoleType ( ) ) ) ;						
		return mapping.findForward ( "titleAuth" );
	}
	
	public  ActionForward doRoleAuth( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		TitleForm titleForm = ( TitleForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request ) ;
		byte cuRoleType =  currentUser.getCurrentUserMaxRoleType ( );
        if ( cuRoleType > Constants.ROLE_TYPE_ORG_MANAGER ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   
		
		byte roleType = titleForm.getRoleType ( ) ;
		if ( roleType <= cuRoleType  ) throw new Exception( Constants.AUTH_ACCESSDENIED ) ; 
		
		TitleMsgVo titleVo = new TitleMsgVo() ; 
		BeanUtils.copyProperties ( titleVo , titleForm );
		titleVo.setOperUser (  currentUser.getUserId ( ) );
		OrgFactory.getTitleManager ( ).saveTitleRoleRel ( titleVo , titleForm.getPrincipalIds ( ) ) ;
		
		StringBuffer to = new StringBuffer() ; 
		to.append ( "titleAction.go?method=loadRoleAuths&titleId=" )
          .append ( titleVo.getTitleId ( ) ).append ( "&roleType=" ).append ( roleType ) ; 
		return new ActionForward( to.toString ( ) ,  true  ) ;
	}
	
	public  ActionForward deleteRoleAuth( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		TitleForm titleForm = ( TitleForm ) form;
		TitleMsgVo titleVo = new TitleMsgVo() ; 
		SessionUserInfo currentUser = getCurrentUser ( request ) ;
        if ( currentUser.getCurrentUserMaxRoleType ( ) > Constants.ROLE_TYPE_ORG_MANAGER ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   
		
		BeanUtils.copyProperties ( titleVo , titleForm );
		Long[] deleteIds = titleForm.getDeleteId ( ) ; 
		OrgFactory.getTitleManager ( ).deleteTitleRoleRel (
				titleVo.getTitleId ( ) , deleteIds , currentUser.getUserId ( ) );
		
		StringBuffer to = new StringBuffer() ; 
		to.append ( "titleAction.go?method=editTitleAuth" ) ;
		to.append ( "&grpId=" ).append ( titleForm.getGrpId ( ) );
		to.append ( "&titleId=" ).append ( titleForm.getTitleId ( ) ) ;
		String ecp = request.getParameter ( "ec_p_" ) ;
		if ( ecp != null && !"".equals ( ecp ) ) to.append ( "&ec_p_=" ).append ( ecp ) ;				
		return new ActionForward( to.toString ( ) , true ) ;
	}
	
    public  ActionForward saveTitle(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
		TitleForm titleForm = ( TitleForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request );
        if ( currentUser.getCurrentUserMaxRoleType ( ) > Constants.ROLE_TYPE_ORG_MANAGER ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   
		
		TitleMsgVo titleVo = new TitleMsgVo ( );
		BeanUtils.copyProperties ( titleVo , titleForm );
		titleVo.setOperUser ( currentUser.getUserId ( ) );
		
		if ( titleForm.isValidTitleId ( ) ) {
			fillUpdtUser ( request , titleVo );
			TitleMsgVo vo = getGroupManager( ).loadTitle(titleVo.getTitleId());
			if ( ! vo.getTitleName ( ).equals ( titleVo.getTitleName ( ) ) ) {
				if ( ( getGroupManager ( ).countTitles ( titleVo ) )
						.longValue ( ) > 0 ) {
					Error error = new Error();
					error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.titlename.already.exist" ) );
					request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
					return mapping.findForward( "glerror" ) ;
				}
			}
			getGroupManager ( ).updateTitle ( titleVo );
		} else {
			fillCrtUser ( request , titleVo );
			if ( ( getGroupManager ( ).countTitles ( titleVo ) ).longValue ( ) > 0 ) {
				Error error = new Error();
				error.setErrorTitle ( OrgMessageManager.get ( ).getMessage ( "org.titlename.already.exist" ) );
				request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
				return mapping.findForward( "glerror" ) ;
			}
			getGroupManager ( ).createTitle ( titleVo );
			StringBuffer to = new StringBuffer( "orgSuccess.go?type=title" ) ;
			to.append ( "&grpId=" ).append ( titleForm.getGrpId ( ) ) ;
			to.append ( "&titleId=" ).append ( titleVo.getTitleId ( ) ) ;
			return new ActionForward( to.toString ( ) , true ) ;
		}
		
		return mapping.findForward ( "success" );
    }

	
	public ActionForward removeTitle ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		TitleForm titleForm = ( TitleForm ) form;
		SessionUserInfo currentUser = getCurrentUser ( request );
        if ( currentUser.getCurrentUserMaxRoleType ( ) > Constants.ROLE_TYPE_ORG_MANAGER ) 
        	throw new Exception( Constants.AUTH_ACCESSDENIED ) ;   
		
		Long operuser = currentUser.getUserId ( );
		getGroupManager ( ).batchRemoveTitles ( titleForm.getDeleteId ( ) ,operuser );
		return mapping.findForward ( "success" );
	}
	
	public ActionForward selectTitle ( ActionMapping mapping , ActionForm form ,
			HttpServletRequest request , HttpServletResponse response )
			throws Exception {
		TitleForm titleForm = ( TitleForm ) form;
		GroupVo groupVo = getGroupManager ( ).loadGroup4SelectOption (	titleForm.getGrpId ( ) );
		titleForm.setGroupVo ( groupVo );
		return mapping.findForward ( "titleSelect" );
	}
	
	private GroupManager getGroupManager ( ) throws CheckException {
		return ( GroupManager ) getBean ( "groupManager" );
	}
}
